package com.r2coding.domain.strategy.model.entity;

import com.r2coding.types.common.Constants;
import com.r2coding.types.enums.StrategyRuleModel;
import lombok.Builder;
import lombok.Data;

import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 抽奖策略规则 充血实体
 *
 * @author caolx
 * @date 2025/7/25 7:27
 */
@Data
@Builder
public class StrategyRuleEntity {
    /**
     * 抽奖策略ID
     */
    private Long strategyId;
    /**
     * 奖品ID
     */
    private Integer awardId;
    /**
     * 抽奖规则类型；1——策略规则、2——奖品规则
     */
    private Integer ruleType;
    /**
     * 抽奖规则类型【rule_random（随机值计算）、rule_lock（抽奖几次后解锁）、rule_luck_award（幸运奖——兜底奖品）】
     */
    private String ruleModel;
    /**
     * 抽奖规则比值
     */
    private String ruleValue;
    /**
     * 抽奖规则描述
     */
    private String ruleDesc;

    /**
     * 获取权重值
     * 数据案例；4000:102,103,104,105;5000:102,103,104,105,106,107;6000:102,103,104,105,106,107,108,109
     *
     * @return key为解锁条件数值，value为对应的奖品列表
     */
    public Map<Integer, List<Integer>> getRuleWeightValues() {
        if (!StrategyRuleModel.WEIGHT.getModel().equals(ruleModel)) {
            return Collections.emptyMap();
        }

        String[] ruleValueGroups = ruleValue.split(Constants.COMMA);
        Map<Integer, List<Integer>> resultMap = new HashMap<>(ruleValueGroups.length);
        for (String ruleValueGroup : ruleValueGroups) {
            // 分割字符串以获取键和值
            String[] parts = ruleValueGroup.split(Constants.COLON);
            if (parts.length != 2) {
                throw new IllegalArgumentException("rule_weight rule_rule invalid input format" + ruleValueGroup);
            }

            // 解析键
            int ruleWeight = Integer.parseInt(parts[0]);
            // 解析值
            String[] valueStrings = parts[1].split(Constants.SPLIT);
            List<Integer> values = Arrays.stream(valueStrings).map(Integer::parseInt).collect(Collectors.toList());
            resultMap.put(ruleWeight, values);
        }
        return resultMap;
    }
}
